//
//  AddressBookReader.m
//  AdressBookConverter
//
//  Created by Daniel Schneller on 15.12.08.
//  Copyright 2008 __MyCompanyName__. All rights reserved.
//

#import "AddressBookReader.h"
#import "AddressBook/AddressBook.h"
#import "AddressBook/AddressBookUI.h"
#import "Foundation/Foundation.h"
#import "FritzXMLTools.h"

@implementation AddressBookReader
-(void)awakeFromNib {
	[generatedXml setString:@""];
}


-(IBAction)saveToFile:(id)sender {
	
	// Create the File Open Dialog class.
	NSSavePanel* savePanel = [NSSavePanel savePanel];
	// Enable directory creation
	[savePanel setCanCreateDirectories:YES];
	
	
	// Display the dialog.  If the OK button was pressed,
	// process the files.
	[savePanel beginSheetForDirectory:nil
								 file:nil 
					   modalForWindow:mainWindow 
						modalDelegate:self
					   didEndSelector:@selector(savePanelDidEnd: returnCode: contextInfo:)
						  contextInfo:nil];
	
	
}


-(IBAction)generateXml:(id)sender {
	NSArray* tPeopleArray = [picker selectedRecords];
	ABPerson* tPerson;
	NSXMLElement* tXmlPhonebook = (NSXMLElement*)[NSXMLNode elementWithName:@"phonebook"];
	NSXMLDocument* tXmlDoc = [[NSXMLDocument alloc]initWithRootElement:tXmlPhonebook];
	[tXmlDoc setVersion:@"1.0"];
	[tXmlDoc setCharacterEncoding:@"ISO-8859-1"];
	FritzXMLTools* fritzXmlTools = [[FritzXMLTools alloc] init];
	
	for (tPerson in tPeopleArray) {
		NSString* tFirstName = [tPerson valueForProperty:kABFirstNameProperty];
		NSString* tMiddleName = [tPerson valueForProperty:kABMiddleNameProperty];
		NSString* tLastName = [tPerson valueForProperty:kABLastNameProperty];
		NSString* tFullname = @"";
		if (tLastName) {
			tFullname = [tFullname stringByAppendingString:tLastName];
		}
		if (tFirstName) {
			tFullname = [tFullname stringByAppendingString:[NSString stringWithFormat:@", %@", tFirstName]];
			if (tMiddleName) {
				tFullname = [tFullname stringByAppendingString:[NSString stringWithFormat:@" %@", tMiddleName]];
			}
		}
		
		NSString* tPhoneHome = nil;
		NSString* tPhoneOffice = nil;
		NSString* tPhoneMobile = nil;
		
		ABMultiValue* tPhones = [tPerson valueForProperty:kABPhoneProperty];
		for (int i = 0; i < [tPhones count]; i++) {
			NSString *tLabel = [tPhones labelAtIndex:i];
			if ([tLabel compare:kABPhoneHomeLabel] == NSOrderedSame) {
				tPhoneHome = [tPhones valueAtIndex:i];
			} else if ([tLabel compare:kABPhoneWorkLabel] == NSOrderedSame) {
				tPhoneOffice = [tPhones valueAtIndex:i];
			} else if ([tLabel compare:kABPhoneMobileLabel] == NSOrderedSame) {
				tPhoneMobile = [tPhones valueAtIndex:i];
			}
		}
		
		NSXMLElement *tXmlContact = [fritzXmlTools contactElementFor:tFullname officePhone:tPhoneOffice homePhone:tPhoneHome mobilePhone: tPhoneMobile];
		BOOL tContactToBeAdded = YES;
		if (!tPhoneMobile && !tPhoneOffice && !tPhoneHome) {
			tContactToBeAdded = [[NSUserDefaults standardUserDefaults] boolForKey:@"includeContactsWithoutNumbers"];
		}
		if (tContactToBeAdded) {
			[tXmlPhonebook addChild:tXmlContact];
		}
	}
	NSString* tResult = [tXmlDoc XMLStringWithOptions:NSXMLNodePrettyPrint];
	tResult = [tResult stringByAppendingString:[fritzXmlTools getPrivatePart]];
	[generatedXml setString:tResult];
	currentDoc = tXmlDoc;
}


#pragma mark selector

- (void)savePanelDidEnd:(NSSavePanel*)sheet 
			 returnCode:(int)returnCode 
			contextInfo:(void*)contextInfo {
	if (returnCode == NSOKButton ){
		// Get the file name
		lastFileName = [sheet filename];
		NSData* tXmlData = [currentDoc XMLDataWithOptions:NSXMLNodePrettyPrint];
		
		if (![tXmlData writeToFile:lastFileName
						atomically:YES]) {
			NSBeep();
			NSLog(@"Could not write document out");
		}
	}
}


@end
